package com.mhl.campuscabinet;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.mhl.adapter.SoldProductAdapter;
import com.mhl.adapter.WaitSoldProductAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.SoldProduct;
import com.mhl.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

// 我卖出的下的未成交订单
public class SellingFragment extends Fragment {

    private List<SoldProduct> soldProductList = new ArrayList<>();
    private WaitSoldProductAdapter adapter;
    //private ArrayList<String> urls = new ArrayList<>();
    //private ArrayList<Integer> tags;
    private boolean flag;
    private int productState;
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            adapter.notifyDataSetChanged();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_selling, container, false);
        loadSellingProducts();
        //test();
        RecyclerView recyclerView = view.findViewById(R.id.recycle_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager((MySoldActivity) getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new WaitSoldProductAdapter(soldProductList, (MySoldActivity) getActivity());
        recyclerView.setAdapter(adapter);
        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
//        flag = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (flag) {
            flag = false;
            loadSellingProducts();
//            test();
            System.out.println("日你妈，退钱");
        }

    }

    // 加载未成交订单
    private void loadSellingProducts() {

        JSONObject userJson = new JSONObject();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            userJson.put("user_id", User.getInstance().getUserId());
            String json = userJson.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "user/merchandise/sold", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String ItemsString = response.body().string();
                    //处理时间
                    String allInfo = "";
                    String beforeT = "";
                    String afterT = "";
                    try {
                        int state = 1;
                        try {
                            JSONObject errcodeJson = new JSONObject(ItemsString);
                            state = errcodeJson.getInt("errcode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //Looper.prepare();
                        if (state != 0) {
                            //Toast.makeText(getActivity(), "Can't load sold list", Toast.LENGTH_SHORT).show();
                            System.out.println("正在卖的 出错！！！！！！！");
                        } else {
                            JSONObject res = new JSONObject(ItemsString);
                            JSONObject data = res.getJSONObject("data");
                            JSONArray merchandiseData = data.getJSONArray("merchandise");
                            for (int i = 0; i < merchandiseData.length(); i++) {

                                JSONObject item = merchandiseData.getJSONObject(i);
                                productState = item.getInt("state");

                                if (productState == 1) {
                                    SoldProduct sProduct = new SoldProduct();
                                    ArrayList<String> urls = new ArrayList<>();
                                    soldProductList.add(sProduct);
                                    sProduct.setPrice(item.getDouble("pre_price"));
                                    sProduct.setName(item.getString("name"));

                                    allInfo = item.getString("order_datetime");
                                    beforeT = allInfo.substring(0, allInfo.indexOf("T"));
                                    afterT = allInfo.substring(beforeT.length() + 1, beforeT.length() + 6);
                                    allInfo = beforeT + "-" + afterT;
                                    sProduct.setTime(allInfo);

                                    sProduct.setBuyer(item.getString("buyer_name"));
                                    sProduct.setSolder(item.getString("provider_name"));
                                    sProduct.setItemId(item.getInt("id"));

                                    JSONArray urlJSON = item.getJSONArray("url_list");
                                    for (int j = 0; j < urlJSON.length(); j++) {
                                        urls.add(urlJSON.getString(j));
                                    }
                                    sProduct.setUrl(urls);
                                }

                                handler.sendEmptyMessage(1);
                            }
                            //Looper.loop();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    // 渲染测试
    private void test() {
        soldProductList.clear();
        for (int i = 0; i < 7; i++) {
            SoldProduct soldProduct1 = new SoldProduct();
            soldProduct1.setName("康师傅牛肉面");
            soldProduct1.setPrice(200);
            soldProduct1.setBuyer("麦田里的大白免");
            soldProduct1.setSolder("joker");
            soldProduct1.setTime("2021-02-21");
            ArrayList<String> urls = new ArrayList<>();
            urls.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200208%2F281ed353179745369814955cb31b02f0.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642953563&t=0d19afab90e64e4e7f7bc0d0a775f27a");
            soldProduct1.setUrl(urls);
            soldProductList.add(soldProduct1);
        }
    }
}